<template>
    <div>
        <el-form ref="ruleFormRef" :model="quesData" :rules="rules" class="question-info">
            <div class="info1">
                <div class="title">
                    <span>题干</span>
                    <el-form-item prop="questionTitle">
                        <el-input v-model="quesData.questionTitle" type="textarea" placeholder="题干，点此编辑（必填）"
                            class="questionTitle-input" />

                        <!-- <div style="border: 1px solid #ccc">
                            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                                :defaultConfig="toolbarConfig" :mode="mode" />
                            <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml"
                                :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                        </div> -->


                    </el-form-item>
                </div>
                <el-divider border-style="dashed" />
            </div>
            <div class="info2">
                <div class="xuanxiang">
                    <span>选项</span>
                    <div>
                        <div class="multiple-xuanxiangzhi">
                            <el-checkbox-group v-model="quesData.questionAnswer"
                                v-for="(optionList, index) in quesData.optionsList" class="checkbox-group">
                                <el-checkbox class="check" :values="englishWordsArr[index]"
                                    :label="englishWordsArr[index]" />
                                <el-input v-model="optionList.value" class="checkbox-input"
                                    placeholder="选项，点此编辑，选中即设置为正确答案（必填）" />
                                <div v-show="display" class="delete iconfont icon-shanchu"
                                    @click="deleteXuanXiang(index)"></div>
                            </el-checkbox-group>
                        </div>
                        <div v-show="display" class="add iconfont icon-tianjia" @click="addXuanXiang">添加选项</div>
                    </div>
                </div>
            </div>
            <div>
                <el-divider border-style="dashed" />
                <div class="info3">
                    <span>解析</span>
                    <el-form-item prop="description">
                        <el-input v-model="quesData.description" type="textarea" placeholder="题目解析，点此编辑（必填）"
                            class="description-input" />
                    </el-form-item>

                </div>
            </div>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, defineExpose, defineEmits, watch, shallowRef, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus';
import { getqueryBankAPI } from '@/api/api'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'



// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
    }, 1500)
})

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}


const route = useRoute()
//选项
const englishWordsArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

const props = defineProps({
    childData: {
        default: {}
    },
    questionId: {
        default: "",
    }
})
const display = ref(true)
//题目内容信息
const quesData = ref({
    //答案
    questionAnswer: [],
    //选项
    optionsList: [],
    //题目
    questionTitle: '',
    //解析
    description: '',
})

const ruleFormRef = ref(null)
const rules = reactive({
    questionTitle: [
        { required: true, message: '请填写题目内容', trigger: 'blur' },
    ],
    optionsList: [
        { required: true, message: 'Please input Activity name', trigger: 'blur' },
    ],
    description: [
        { required: true, message: '请填写解析，若无请写‘无数据’', trigger: 'blur' },
    ],
    questionAnswer: [
        { type: "array", required: true, message: "请至少选择一个选项", trigger: 'change' },
    ],
})

onMounted(() => {
    if (quesData.value.optionsList.length == 0) {
        for (let i = 0; i < 4; i++) {
            quesData.value.optionsList.push({
                text: englishWordsArr[quesData.value.optionsList.length],
                value: ""
            })
        }
    }
    if (route.path.includes('checkQuestion')) {
        display.value = false
    }
    if (props.questionId) {
        //查询题目
        getqueryBankAPI(props.questionId).then(res => {
            if (res.data.code == 200) {
                res.data.data.questionAnswer = JSON.parse(res.data.data.questionAnswer)
                res.data.data.optionsList = JSON.parse(res.data.data.optionsList)
                quesData.value = res.data.data
            }
        })
    }
})

//watch侦听getter函数  () =>
watch(() => props.childData, (value) => {
    quesData.value = value
}, { deep: true })
watch(() => quesData.value, (value) => {
    emit('update:childData', value)
}, { deep: true })

//将选择题里的值传给父组件
const addData = ref([])
const emit = defineEmits(['choiceChild-click', 'update:childData'])
//添加题目
const choiceData = () => {
    //判断答案不为空
    if (quesData.value.questionAnswer.length != 0) {
        //判断选项值不为空
        const optionsData = quesData.value.optionsList
        console.log(optionsData.value, 'optionsData');
        const isCompleteness = optionsData.every((obj) => {
            return Object.values(obj).every((value) => value !== "");
        });
        console.log(isCompleteness, 'isCompleteness');
        if (isCompleteness) {
            ruleFormRef.value.validate((valid) => {
                if (valid) {
                    //成功再提交数据
                    let isSingleSelect = 1
                    if (quesData.value.questionAnswer.length == 1) {
                        isSingleSelect = 0
                    }
                    addData.value.push({
                        questionTitle: quesData.value.questionTitle,
                        questionAnswer: JSON.stringify(quesData.value.questionAnswer),
                        isSingleSelect: isSingleSelect,
                        optionsList: JSON.stringify(Object.assign([], quesData.value.optionsList)),
                        description: quesData.value.description,
                    })
                    emit('choiceChild-click', addData.value);
                } else {
                    console.log("未通过");
                }
            });
        } else {
            ElMessage.warning('请填写完整的选项值')
        }
    } else {
        ElMessage.warning('请至少选择一个答案')
    }
}
//重置数据
const choiceClearData = () => {
    quesData.value.questionTitle = ''
    quesData.value.optionsList = []
    quesData.value.questionAnswer = []
    quesData.value.description = ''
    if (quesData.value.optionsList.length == 0) {
        for (let i = 0; i < 4; i++) {
            quesData.value.optionsList.push({
                text: englishWordsArr[quesData.value.optionsList.length],
                value: ""
            })
        }
    }
}
defineExpose({
    choiceData, choiceClearData
})

//添加选项
const addXuanXiang = () => {
    if (quesData.value.optionsList.length < englishWordsArr.length) {
        quesData.value.optionsList.push({
            text: englishWordsArr[quesData.value.optionsList.length],
            value: ""
        })
    } else {
        ElMessage.warning('最多可有十个选项')
    }
}

//删除选项
const deleteXuanXiang = (index) => {
    if (quesData.value.optionsList.length > 2) {
        quesData.value.optionsList.splice(index, 1)
    } else {
        ElMessage.warning('至少需要两个选项')
    }
}


</script>

<style lang="less" scoped>
.question-info {

    .info1 {

        .title {
            margin-top: 25px;
            display: flex;
            // justify-content: center;

            span {
                font-size: small;
                min-width: 30px;
                height: 20px;
                margin: 15px 20px 0 20px;
                background-color: #E5EAF3;
                padding: 0 15px;
            }

            .questionTitle-input {
                width: 800px;

            }
        }

    }

    .info2 {
        display: flex;
        // justify-content: center;

        .buttons {
            display: flex;
            justify-content: end;

            .button1 {
                margin: 0 50px 20px 20px;
                font-size: small;

            }
        }

        .xuanxiang {
            display: flex;

            span {
                font-size: small;
                min-width: 30px;
                height: 20px;
                margin: 15px 20px 0 20px;
                background-color: #E5EAF3;
                padding: 0 15px;
            }


            .multiple-xuanxiangzhi {
                display: block;

                .checkbox-group {
                    display: flex;
                    text-align: center;
                }

                .check {
                    margin: 5px 0 0 10px;
                }

                .checkbox-input {
                    width: 730px;
                    margin-left: 20px;
                    padding: 5px 0;
                }

                .delete {
                    color: #636466;
                    margin: 19px 10px;
                }

                .delete:hover {
                    color: #409EFF;
                    cursor: pointer;
                }
            }

            .add {
                color: #409EFF;
                margin: 10px 0 0 10px;
            }

            .add:hover {
                cursor: pointer;
            }
        }
    }

    .info3 {
        display: flex;
        // justify-content: center;
        margin-bottom: 15px;

        span {
            font-size: small;
            width: 30px;
            height: 20px;
            margin: 15px 20px;
            background-color: #E5EAF3;
            padding: 0 15px;
        }

        .description-input {
            width: 800px;

        }
    }

    /deep/ .el-radio__input.is-checked .el-radio__inner::after {
        content: '';
        width: 8px;
        height: 3px;
        border: 2px solid white;
        border-top: transparent;
        border-right: transparent;
        text-align: center;
        display: block;
        position: absolute;
        top: 2px;
        left: 1px;
        transform: rotate(-45deg);
        border-radius: 0px;
        background: none;
    }

}
</style>
